<template>
  <div class="app-container">
    <el-dialog title="编辑复杂属性" :visible.sync="open" width="85%" :close-on-click-modal="false" append-to-body @close="cancel">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="代码" prop="basicCode">
          <el-input v-model="queryParams.basicCode" placeholder="请输入代码" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="名称" prop="basicName">
          <el-input v-model="queryParams.basicName" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button key="complexAdd" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button key="complexDel" type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="fieldList" @selection-change="handleSelectionChange" style="border: 1px solid #e6ebf5;" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="代码" align="center" prop="basicCode" sortable :show-overflow-tooltip="true"/>
        <!--        <el-table-column label="最终代码" align="center" prop="finalBasicCode" sortable :show-overflow-tooltip="true"/>-->
        <el-table-column label="名称" align="center" prop="basicName" sortable />
        <el-table-column label="数据类型" align="center" prop="basicJavaType" sortable>
          <template slot-scope="scope">
            <dict-tag :options="dict.type.basic_java_type" :value="scope.row.basicJavaType" />
          </template>
        </el-table-column>
        <el-table-column label="页面元素" align="center" prop="formTypeName" sortable>
          <template slot-scope="scope">
            <dict-tag :options="dict.type.form_type_name" :value="scope.row.formTypeName" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="排序" align="center" prop="sortNum" sortable />-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" >修改</el-button>
            <el-button v-if="scope.row.dataExtend == 'true'" size="mini" type="text" icon="el-icon-edit" @click="editComplex(scope.row)" >编辑复杂属性</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="isOpen" width="60%" :close-on-click-modal="false" append-to-body @close="cancelForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="代码" prop="basicCode">
              <el-input v-if="form.basicCode == '_RESPONUSERNAME' || form.basicCode == '_EXECUTORNAME' || form.basicCode == '_CHECKUSERNAME' || form.basicCode == '_RESPONDEPTNAME'" readonly maxlength="40" v-model="form.basicCode" placeholder="请输入代码" />
              <el-input v-else maxlength="40" v-model="form.basicCode" placeholder="请输入代码" />
            </el-form-item>

          </el-col>
          <el-col :span="11">
            <el-form-item label="名称" prop="basicName" >
              <el-input v-model="form.basicName" placeholder="请输入名称" />
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="排序" prop="sortNum">
              <el-input-number v-model="form.sortNum" placeholder="请输入排序" style="width:100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
          </el-col>
        </el-row>

        <el-row >
          <el-col >
            <el-form-item label="数据类型"   prop="dataType">
              <div  style="border: 1px solid #e6ebf5;width: 90%;">
                <div style="margin-left:30px;margin-top:20px;">
                  <span>文本：</span>
                  <el-radio @change="setFormData" style="margin-left:10px;" v-model="dataType"  label="text_1">普通文本</el-radio>
                  <el-radio @change="setFormData"  v-model="dataType"  label="text_2">多行文本</el-radio>
                  <el-radio @change="setFormData"  v-model="dataType"  label="text_3">富文本</el-radio>
                </div>

                <div style="margin-left:30px;margin-top:10px;">
                  <span>数字：</span>
                  <el-radio @change="setFormData" style="margin-left:10px;" v-model="dataType" label="num_1">整数</el-radio>
                  <el-radio @change="setFormData"  v-model="dataType" label="num_2">小数</el-radio>
                </div>

                <div style="margin-left:30px;margin-top:10px;">
                  <span>日期：</span>
                  <el-radio @change="setFormData" style="margin-left:10px;" v-model="dataType" label="date_1">日期</el-radio>
                  <el-radio @change="setFormData" v-model="dataType" label="date_2">日期时间</el-radio>
                </div>

                <div style="margin-left:30px;margin-top:10px;">
                  <span>字典：</span>
                  <el-radio @change="setFormData" style="margin-left:10px;" v-model="dataType" label="dic_1">下拉单选</el-radio>
                  <el-radio @change="setFormData" v-model="dataType" label="dic_2">下拉多选</el-radio>
                  <el-radio @change="setFormData" v-model="dataType" label="dic_3">树单选</el-radio>
                  <el-radio @change="setFormData" v-model="dataType" label="dic_4">树多选</el-radio>
                  <el-radio @change="setFormData" v-model="dataType" label="dic_6">单选(radio)</el-radio>
                  <el-radio @change="setFormData" v-model="dataType" label="dic_7"> 多选(checkbox)</el-radio>
                </div>

                <div style="margin-left:30px;margin-top:10px;">
                  <span>附件：</span>
                  <el-radio @change="setFormData" style="margin-left:10px;" v-model="dataType" label="file_1">普通附件</el-radio>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="是否必填" v-if="this.form.dataExtend == 'false'">
              <el-switch v-model="form.jsRequired" active-value="1" inactive-value="0" ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="是否只读" v-if="this.form.dataExtend == 'false'">
              <el-switch v-model="form.isReadOnly" active-value="1" inactive-value="0" ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <!-- TODO -->
            <el-form-item label="上传类型" v-if="form.dataExtend == 'false'&&(form.formTypeName == 'upload')">
              <el-select clearable v-model="form.uploadtypeId" placeholder="请选择上传类型" style="width: 80%;">
                <el-option
                  v-for="upload in uploadTypeList"
                  :key="upload.id"
                  :label="upload.name"
                  :value="upload.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="字典" v-if=" form.dataExtend == 'false'&&(
             form.formTypeName == 'selectsingle'
            ||form.formTypeName == 'selectmulti'
            ||form.formTypeName == 'selectztree'
            ||form.formTypeName == 'selectztreemulti'
            ||form.formTypeName == 'selectztreecustomcheck'
            ||form.formTypeName == 'radio'
            ||form.formTypeName == 'checkbox'
            )">
              <el-select clearable v-model="form.formDictType" style="width: 90%;">
                <el-option
                  key=""
                  label="请选择"
                  value=""
                ></el-option>
                <el-option
                  v-for="dict in dictList"
                  :key="dict.dictType"
                  :label="dict.dictName"
                  :value="dict.dictType"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>

            <el-form-item label="默认值" v-if=" form.dataExtend == 'false'&&(
             form.formTypeName == 'selectsingle'
            ||form.formTypeName == 'selectmulti'
            ||form.formTypeName == 'selectztree'
            ||form.formTypeName == 'selectztreemulti'
            ||form.formTypeName == 'selectztreecustomcheck'
            ||form.formTypeName == 'radio'
            ||form.formTypeName == 'checkbox'
            )">
              <el-input v-model="form.defaultValue" placeholder="请输入默认值" style="width: 90%;"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listField, getField, delField, addField, updateField, getCodeSortNum, basicCodeValid } from "@/api/form/field";
import { listType as uploadTypeList } from "@/api/form/uploadtype";
import { optionselect } from '@/api/system/dict/type'
export default {
  name: "Field",
  dicts: ['basic_java_type', 'form_type_name', 'data_extend'],
  data () {
    var ValidCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('代码不能为空'));
      } else {
        basicCodeValid(value, this.id, this.queryParams.parentId).then(data => {
          if (data == '1') {
            callback(new Error('已经存在该代码'));
          } else {
            callback();
          }
        });
      }
    };
    return {
      uploadTypeList: [],
      selectList: [],
      dataType:'text_1',
      id: '',
      flag: '1',//1：新增，2：修改
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      fieldList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isOpen: false,
      dictList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        basicCode: null,
        basicName: null
      },
      // 表单参数
      form: { formwidth: 200 },
      // 表单校验
      rules: {
        basicName: [
          { required: true, trigger: "blur", message: "名称不能为空" }
        ], dataExtend: [
          { required: true, trigger: "blur", message: "字段类型不能为空" }
        ], basicCode: [
          { required: true,validator: ValidCode, trigger: "blur", message: "代码不能为空" }
        ],
      },
      componentList: []
    };
  },
  created() {
    uploadTypeList().then(data => {
      this.uploadTypeList = data.rows;
    });
  },
  methods: {
    //设置数据类型、页面元素
    setFormData(){
      let type = this.dataType;
      //重置查看方式表单校验
      if (type=='text_1') { //普通文本
        this.form.basicJavaType='string';
        this.form.dataExtend='false';
        this.form.formTypeName='input';
      } else if (type=='text_2') { //多行文本
        this.form.basicJavaType='string';
        this.form.dataExtend='false';
        this.form.formTypeName='textarea';
      } else if (type=='text_3') { //富文本
        this.form.basicJavaType='string';
        this.form.dataExtend='false';
        this.form.formTypeName='richtext';
      } else if (type=='num_1') { //整数
        this.form.basicJavaType='int';
        this.form.dataExtend='false';
        this.form.formTypeName='spinner';
      } else if (type=='num_2') { //小数
        this.form.basicJavaType='double';
        this.form.dataExtend='false';
        this.form.formTypeName='spinner';
      } else if (type=='date_1') { //日期
        this.form.basicJavaType='date';
        this.form.dataExtend='false';
        this.form.formTypeName='date';
      }else if (type=='date_2') { //日期时间
        this.form.basicJavaType='datetime';
        this.form.dataExtend='false';
        this.form.formTypeName='datetime';
      } else if(type=='dic_1') { //下拉单选
        this.form.basicJavaType='string';
        this.form.dataExtend='false';
        this.form.formTypeName='selectsingle';
      } else if (type=='dic_2') { //下拉多选
        this.form.basicJavaType='string';
        this.form.dataExtend='false';
        this.form.formTypeName='selectmulti';
      } else if(type=='dic_3') { //树单选
        this.form.basicJavaType='string';
        this.form.dataExtend='false';
        this.form.formTypeName='selectztree';
      } else if (type=='dic_4') { //树多选(含父子节点)
        this.form.basicJavaType='string';
        this.form.dataExtend='false';
        this.form.formTypeName='selectztreemulti';
      } else if (type=='dic_8') { //树多选(不含父子节点)
        this.form.basicJavaType='string';
        this.form.dataExtend='false';
        this.form.formTypeName='selectztreecustomcheck';
      } else if (type=='dic_6') { //单选(radio)
        this.form.basicJavaType = 'string';
        this.form.dataExtend = 'false';
        this.form.formTypeName = 'radio';
      } else if (type=='dic_7') { //多选(checkbox)
        this.form.basicJavaType = 'string';
        this.form.dataExtend = 'false';
        this.form.formTypeName = 'checkbox';
      } else if (type=='file_1') { //普通附件
        this.form.basicJavaType='';
        this.form.dataExtend='false';
        this.form.formTypeName='upload';
      } else if (type=='table_1') {    //表格(复杂属性)
        this.form.basicJavaType='';
        this.form.dataExtend='true';
        this.form.formTypeName='';
      } else if(type=='upload_folder') {
        // 文件夹上传
        this.form.basicJavaType='';
        this.form.dataExtend='false';
        this.form.formTypeName='upload_folder';
      }
    },
    //设置数据类型用来反显
    setDataType(){
      if(this.form.dataExtend!='true') {
        if (this.form.basicJavaType == 'string' && this.form.formTypeName == 'input') { //普通文本
          this.dataType = 'text_1';
        } else if (this.form.formTypeName == 'textarea') { //多行文本
          this.dataType = 'text_2';
        } else if (this.form.formTypeName == 'richtext') { //富文本
          this.dataType = 'text_3';
        }
        if (this.form.basicJavaType == 'int') { //整数
          this.dataType = 'num_1';
        } else if (this.form.basicJavaType == 'double') { //小数
          this.dataType = 'num_2';
        }
        if (this.form.formTypeName == 'date') { //日期
          this.dataType = 'date_1';
        } else if (this.form.formTypeName == 'datetime') { //日期时间
          this.dataType = 'date_2';
        } else if (this.form.formTypeName == 'selectsingle') { //下拉单选
          this.dataType = 'dic_1';
        } else if (this.form.formTypeName == 'selectmulti') { //下拉多选
          this.dataType = 'dic_2';
        } else if (this.form.formTypeName == 'selectztreemulti') { //树多选(含父子节点)
          this.dataType = 'dic_4';
        } else if (this.form.formTypeName == 'selectztreecustomcheck') { //树多选(不含父子节点)
          this.dataType = 'dic_8';
        } else if (this.form.formTypeName == 'radio') { //单选(radio)
          this.dataType = 'dic_6';
        } else if (this.form.formTypeName == 'checkbox') { //多选(checkbox)
          this.dataType = 'dic_7';
        } else if (this.form.formTypeName == 'upload') { //普通附件
          this.dataType = 'file_1';
        } else if (this.form.formTypeName == 'upload_folder') { // 文件夹上传
          this.dataType = 'upload_folder';
        }
      } else if (this.form.dataExtend=='true') { //表格(复杂属性)
        this.dataType = 'table_1';
      }
      this.form.dataType = this.dataType;
    },
    showDialog (pid) {
      this.open = true;
      this.queryParams.parentId = pid;
      console.log('pid: ' + pid)
      this.getList();
    },
    chDataExtend (val) {
      this.form.basicJavaType = '';
      this.form.formDictType = '';
      this.form.formwidth = 200;
      if (val == 'true') {
        this.form.formTypeName = null;
        this.form.jsRequired = null;
        this.form.isReadOnly = null;
        this.form.isShow = null;
        this.form.isAddDelFlag = '1';
      } else if (val == 'false') {
        this.form.formTypeName = 'input';
        this.form.jsRequired = '0';
        this.form.isReadOnly = '0';
        this.form.isShow = '1';
        this.form.isAddDelFlag = null;
      }
    },
    /** 查询列表 */
    getList () {
      this.loading = true;
      listField(this.queryParams).then(response => {
        this.fieldList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    cancelForm () {
      this.isOpen = false;
    },
    // 表单重置
    reset (basicCode, sortNum) {
      this.form = {
        id: null,
        createTime: null,
        createUser: null,
        delFlag: null,
        remarks: null,
        sortNum: sortNum,
        updateTime: null,
        updateUser: null,
        hierarchy: null,
        parentId: null,
        parentIds: null,
        basicCode: basicCode,
        basicColType: null,
        basicFormula: null,
        basicJavaType: '',
        basicLength: null,
        basicName: null,
        dataExtend: 'false',
        dataGenStratgy: null,
        dataUnit: null,
        formDictType: '',
        formTypeName: 'input',
        defaultValue: null,
        formwidth: null,
        isShow: '1',
        jsMatchWhat: null,
        jsRequired: '0',
        modelId: null,
        uploadtypeId: null,
        rowspan: null,
        frontGridId: null,
        displayNumber: null,
        isOnly: null,
        isReadOnly: '0',
        isAddDelFlag: '1',
        isHighLight: null,
        imgid: null,
        componentId: null,
        dataType:''
      };
      this.resetForm("form");

      this.dataType='text_1';
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.id = '';
      getCodeSortNum().then(data => {
        let dataArr = data.split(':');
        optionselect().then(res => {
          if (res.data != null) {
            this.dictList = res.data;
          }
          this.reset(dataArr[0], dataArr[1]);
          this.form.formwidth = 200
          this.isOpen = true;
          this.title = "添加";
        });
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      this.id = row.id
      getField(row.id).then(response => {
        this.form = response.data;
        this.isOpen = true;
        this.title = "修改";
        //反显数据类型
        this.setDataType();
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateField(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.isOpen = false;
              this.getList();
            });
          } else {
            this.form.parentId = this.queryParams.parentId;
            addField(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.isOpen = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据项？').then(function () {
        return delField(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('system/field/export', {
        ...this.queryParams
      }, `field_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
